using System;

namespace Beeflys
{
    sealed class SponsorTimer : ISponsorTimer, ITimerTask
    {
        public static ISponsorTimer Get(TimeSpan timeSpan)
        {
            if(timeSpan == Timer.DefaultTimeSpan || timeSpan == TimeSpan.Zero)
            {
                return SponsorEmptyTimer.EmptyTimer;
            }

            return new SponsorTimer();
        }

        private ITimeout timeout;
        private Action timeoutAction;
        private volatile bool completed = false;
        
        public bool Completed => this.completed;

        public void Start(TimeSpan timeSpan)
        {
            this.timeout = Timer.Current.CreateTimeout(this, timeSpan);
        }

        public void RegisterTimeoutEvent(Action action)
        {
            this.timeoutAction += action;
        }

        public void RemoveTimeoutEvent(Action action)
        {
            this.timeoutAction -= action;
        }

        public void Stop()
        {
            if(this.timeout.Cancelled || this.timeout.Expired)
            {
                return;
            }

            this.timeout.Cancel();
            this.completed = true;
        }

        public void Run(ITimeout timeout)
        {
            this.completed = true;

            if(this.timeoutAction != null)
            {
                this.timeoutAction();
            }
        }

        
    }
}
